home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / test / regrtest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-10-18  |  30.0 KB  |  822 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Regression test.
  5.  
  6. This will find all modules whose name is "test_*" in the test
  7. directory, and run them.  Various command line options provide
  8. additional facilities.
  9.  
  10. Command line options:
  11.  
  12. -v: verbose    -- run tests in verbose mode with output to stdout
  13. -q: quiet      -- don\'t print anything except if a test fails
  14. -g: generate   -- write the output file for a test instead of comparing it
  15. -x: exclude    -- arguments are tests to *exclude*
  16. -s: single     -- run only a single test (see below)
  17. -r: random     -- randomize test execution order
  18. -f: fromfile   -- read names of tests to run from a file (see below)
  19. -l: findleaks  -- if GC is available detect tests that leak memory
  20. -u: use        -- specify which special resource intensive tests to run
  21. -h: help       -- print this text and exit
  22. -t: threshold  -- call gc.set_threshold(N)
  23. -T: coverage   -- turn on code coverage using the trace module
  24. -D: coverdir   -- Directory where coverage files are put
  25. -N: nocoverdir -- Put coverage files alongside modules
  26. -L: runleaks   -- run the leaks(1) command just before exit
  27. -R: huntrleaks -- search for reference leaks (needs debug build, v. slow)
  28.  
  29. If non-option arguments are present, they are names for tests to run,
  30. unless -x is given, in which case they are names for tests not to run.
  31. If no test names are given, all tests are run.
  32.  
  33. -v is incompatible with -g and does not compare test output files.
  34.  
  35. -T turns on code coverage tracing with the trace module.
  36.  
  37. -D specifies the directory where coverage files are put.
  38.  
  39. -N Put coverage files alongside modules.
  40.  
  41. -s means to run only a single test and exit.  This is useful when
  42. doing memory analysis on the Python interpreter (which tend to consume
  43. too many resources to run the full regression test non-stop).  The
  44. file /tmp/pynexttest is read to find the next test to run.  If this
  45. file is missing, the first test_*.py file in testdir or on the command
  46. line is used.  (actually tempfile.gettempdir() is used instead of
  47. /tmp).
  48.  
  49. -f reads the names of tests from the file given as f\'s argument, one
  50. or more test names per line.  Whitespace is ignored.  Blank lines and
  51. lines beginning with \'#\' are ignored.  This is especially useful for
  52. whittling down failures involving interactions among tests.
  53.  
  54. -L causes the leaks(1) command to be run just before exit if it exists.
  55. leaks(1) is available on Mac OS X and presumably on some other
  56. FreeBSD-derived systems.
  57.  
  58. -R runs each test several times and examines sys.gettotalrefcount() to
  59. see if the test appears to be leaking references.  The argument should
  60. be of the form stab:run:fname where \'stab\' is the number of times the
  61. test is run to let gettotalrefcount settle down, \'run\' is the number
  62. of times further it is run and \'fname\' is the name of the file the
  63. reports are written to.  These parameters all have defaults (5, 4 and
  64. "reflog.txt" respectively), so the minimal invocation is \'-R ::\'.
  65.  
  66. -u is used to specify which special resource intensive tests to run,
  67. such as those requiring large file support or network connectivity.
  68. The argument is a comma-separated list of words indicating the
  69. resources to test.  Currently only the following are defined:
  70.  
  71.     all -       Enable all special resources.
  72.  
  73.     audio -     Tests that use the audio device.  (There are known
  74.                 cases of broken audio drivers that can crash Python or
  75.                 even the Linux kernel.)
  76.  
  77.     curses -    Tests that use curses and will modify the terminal\'s
  78.                 state and output modes.
  79.  
  80.     largefile - It is okay to run some test that may create huge
  81.                 files.  These tests can take a long time and may
  82.                 consume >2GB of disk space temporarily.
  83.  
  84.     network -   It is okay to run tests that use external network
  85.                 resource, e.g. testing SSL support for sockets.
  86.  
  87.     bsddb -     It is okay to run the bsddb testsuite, which takes
  88.                 a long time to complete.
  89.  
  90.     decimal -   Test the decimal module against a large suite that
  91.                 verifies compliance with standards.
  92.  
  93.     compiler -  Test the compiler package by compiling all the source
  94.                 in the standard library and test suite.  This takes
  95.                 a long time.
  96.  
  97.     subprocess  Run all tests for the subprocess module.
  98.  
  99. To enable all resources except one, use \'-uall,-<resource>\'.  For
  100. example, to run all the tests except for the bsddb tests, give the
  101. option \'-uall,-bsddb\'.
  102. '''
  103. import os
  104. import sys
  105. import getopt
  106. import random
  107. import warnings
  108. import sre
  109. import cStringIO
  110. import traceback
  111. warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '.*test.test_grammar$')
  112. if sys.maxint > 2147483647:
  113.     warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '<string>')
  114.  
  115. if sys.platform == 'darwin':
  116.     
  117.     try:
  118.         import resource
  119.     except ImportError:
  120.         pass
  121.  
  122.     (soft, hard) = resource.getrlimit(resource.RLIMIT_STACK)
  123.     newsoft = min(hard, max(soft, 1024 * 2048))
  124.     resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  125.  
  126. from test import test_support
  127. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb', 'decimal', 'compiler', 'subprocess')
  128.  
  129. def usage(code, msg = ''):
  130.     print __doc__
  131.     if msg:
  132.         print msg
  133.     
  134.     sys.exit(code)
  135.  
  136.  
  137. def main(tests = None, testdir = None, verbose = 0, quiet = False, generate = False, exclude = False, single = False, randomize = False, fromfile = None, findleaks = False, use_resources = None, trace = False, coverdir = 'coverage', runleaks = False, huntrleaks = False):
  138.     """Execute a test suite.
  139.  
  140.     This also parses command-line options and modifies its behavior
  141.     accordingly.
  142.  
  143.     tests -- a list of strings containing test names (optional)
  144.     testdir -- the directory in which to look for tests (optional)
  145.  
  146.     Users other than the Python test suite will certainly want to
  147.     specify testdir; if it's omitted, the directory containing the
  148.     Python test suite is searched for.
  149.  
  150.     If the tests argument is omitted, the tests listed on the
  151.     command-line will be used.  If that's empty, too, then all *.py
  152.     files beginning with test_ will be used.
  153.  
  154.     The other default arguments (verbose, quiet, generate, exclude, single,
  155.     randomize, findleaks, use_resources, trace and coverdir) allow programmers
  156.     calling main() directly to set the values that would normally be set by
  157.     flags on the command line.
  158.     """
  159.     test_support.record_original_stdout(sys.stdout)
  160.     
  161.     try:
  162.         (opts, args) = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:', [
  163.             'help',
  164.             'verbose',
  165.             'quiet',
  166.             'generate',
  167.             'exclude',
  168.             'single',
  169.             'random',
  170.             'fromfile',
  171.             'findleaks',
  172.             'use=',
  173.             'threshold=',
  174.             'trace',
  175.             'coverdir=',
  176.             'nocoverdir',
  177.             'runleaks',
  178.             'huntrleaks='])
  179.     except getopt.error:
  180.         msg = None
  181.         usage(2, msg)
  182.  
  183.     if use_resources is None:
  184.         use_resources = []
  185.     
  186.     for o, a in opts:
  187.         if o in ('-h', '--help'):
  188.             usage(0)
  189.             continue
  190.         if o in ('-v', '--verbose'):
  191.             verbose += 1
  192.             continue
  193.         if o in ('-q', '--quiet'):
  194.             quiet = True
  195.             verbose = 0
  196.             continue
  197.         if o in ('-g', '--generate'):
  198.             generate = True
  199.             continue
  200.         if o in ('-x', '--exclude'):
  201.             exclude = True
  202.             continue
  203.         if o in ('-s', '--single'):
  204.             single = True
  205.             continue
  206.         if o in ('-r', '--randomize'):
  207.             randomize = True
  208.             continue
  209.         if o in ('-f', '--fromfile'):
  210.             fromfile = a
  211.             continue
  212.         if o in ('-l', '--findleaks'):
  213.             findleaks = True
  214.             continue
  215.         if o in ('-L', '--runleaks'):
  216.             runleaks = True
  217.             continue
  218.         if o in ('-t', '--threshold'):
  219.             import gc
  220.             gc.set_threshold(int(a))
  221.             continue
  222.         if o in ('-T', '--coverage'):
  223.             trace = True
  224.             continue
  225.         if o in ('-D', '--coverdir'):
  226.             coverdir = os.path.join(os.getcwd(), a)
  227.             continue
  228.         if o in ('-N', '--nocoverdir'):
  229.             coverdir = None
  230.             continue
  231.         if o in ('-R', '--huntrleaks'):
  232.             huntrleaks = a.split(':')
  233.             if len(huntrleaks) != 3:
  234.                 print a, huntrleaks
  235.                 usage(2, '-R takes three colon-separated arguments')
  236.             
  237.             if len(huntrleaks[0]) == 0:
  238.                 huntrleaks[0] = 5
  239.             else:
  240.                 huntrleaks[0] = int(huntrleaks[0])
  241.             if len(huntrleaks[1]) == 0:
  242.                 huntrleaks[1] = 4
  243.             else:
  244.                 huntrleaks[1] = int(huntrleaks[1])
  245.             if len(huntrleaks[2]) == 0:
  246.                 huntrleaks[2] = 'reflog.txt'
  247.             
  248.         len(huntrleaks[2]) == 0
  249.         if o in ('-u', '--use'):
  250.             u = [ x.lower() for x in a.split(',') ]
  251.             for r in u:
  252.                 remove = False
  253.                 if r[0] == '-':
  254.                     remove = True
  255.                     r = r[1:]
  256.                 
  257.                 if r not in RESOURCE_NAMES:
  258.                     usage(1, 'Invalid -u/--use option: ' + a)
  259.                 
  260.                 if remove:
  261.                     if r in use_resources:
  262.                         use_resources.remove(r)
  263.                     
  264.                 r in use_resources
  265.                 if r not in use_resources:
  266.                     use_resources.append(r)
  267.                     continue
  268.             
  269.     
  270.     if generate and verbose:
  271.         usage(2, "-g and -v don't go together!")
  272.     
  273.     if single and fromfile:
  274.         usage(2, "-s and -f don't go together!")
  275.     
  276.     good = []
  277.     bad = []
  278.     skipped = []
  279.     resource_denieds = []
  280.     if findleaks:
  281.         
  282.         try:
  283.             import gc
  284.         except ImportError:
  285.             print 'No GC available, disabling findleaks.'
  286.             findleaks = False
  287.  
  288.         found_garbage = []
  289.     
  290.     if single:
  291.         gettempdir = gettempdir
  292.         import tempfile
  293.         filename = os.path.join(gettempdir(), 'pynexttest')
  294.         
  295.         try:
  296.             fp = open(filename, 'r')
  297.             next = fp.read().strip()
  298.             tests = [
  299.                 next]
  300.             fp.close()
  301.         except IOError:
  302.             pass
  303.         except:
  304.             None<EXCEPTION MATCH>IOError
  305.         
  306.  
  307.     None<EXCEPTION MATCH>IOError
  308.     if fromfile:
  309.         tests = []
  310.         fp = open(fromfile)
  311.         for line in fp:
  312.             guts = line.split()
  313.             if guts and not guts[0].startswith('#'):
  314.                 tests.extend(guts)
  315.                 continue
  316.         
  317.         fp.close()
  318.     
  319.     if args:
  320.         args = map(removepy, args)
  321.     
  322.     if tests:
  323.         tests = map(removepy, tests)
  324.     
  325.     stdtests = STDTESTS[:]
  326.     nottests = NOTTESTS[:]
  327.     if exclude:
  328.         for arg in args:
  329.             if arg in stdtests:
  330.                 stdtests.remove(arg)
  331.                 continue
  332.         
  333.         nottests[:0] = args
  334.         args = []
  335.     
  336.     if not tests and args:
  337.         pass
  338.     tests = findtests(testdir, stdtests, nottests)
  339.     if single:
  340.         tests = tests[:1]
  341.     
  342.     if randomize:
  343.         random.shuffle(tests)
  344.     
  345.     if trace:
  346.         import trace
  347.         tracer = trace.Trace(ignoredirs = [
  348.             sys.prefix,
  349.             sys.exec_prefix], trace = False, count = True)
  350.     
  351.     test_support.verbose = verbose
  352.     test_support.use_resources = use_resources
  353.     save_modules = sys.modules.keys()
  354.     for test in tests:
  355.         if not quiet:
  356.             print test
  357.             sys.stdout.flush()
  358.         
  359.         if trace:
  360.             tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', globals = globals(), locals = vars())
  361.         else:
  362.             ok = runtest(test, generate, verbose, quiet, testdir, huntrleaks)
  363.             if ok > 0:
  364.                 good.append(test)
  365.             elif ok == 0:
  366.                 bad.append(test)
  367.             else:
  368.                 skipped.append(test)
  369.                 if ok == -2:
  370.                     resource_denieds.append(test)
  371.                 
  372.         if findleaks:
  373.             gc.collect()
  374.             if gc.garbage:
  375.                 print 'Warning: test created', len(gc.garbage), 'uncollectable object(s).'
  376.                 found_garbage.extend(gc.garbage)
  377.                 del gc.garbage[:]
  378.             
  379.         
  380.         for module in sys.modules.keys():
  381.             if module not in save_modules and module.startswith('test.'):
  382.                 test_support.unload(module)
  383.                 continue
  384.         
  385.     
  386.     good.sort()
  387.     bad.sort()
  388.     skipped.sort()
  389.     if good and not quiet:
  390.         if not bad and not skipped and len(good) > 1:
  391.             print 'All',
  392.         
  393.         print count(len(good), 'test'), 'OK.'
  394.         if verbose:
  395.             print "CAUTION:  stdout isn't compared in verbose mode:"
  396.             print 'a test that passes in verbose mode may fail without it.'
  397.         
  398.     
  399.     if bad:
  400.         print count(len(bad), 'test'), 'failed:'
  401.         printlist(bad)
  402.     
  403.     if skipped and not quiet:
  404.         print count(len(skipped), 'test'), 'skipped:'
  405.         printlist(skipped)
  406.         e = _ExpectedSkips()
  407.         plat = sys.platform
  408.         if e.isvalid():
  409.             surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  410.             if surprise:
  411.                 print count(len(surprise), 'skip'), 'unexpected on', plat + ':'
  412.                 printlist(surprise)
  413.             else:
  414.                 print 'Those skips are all expected on', plat + '.'
  415.         else:
  416.             print 'Ask someone to teach regrtest.py about which tests are'
  417.             print 'expected to get skipped on', plat + '.'
  418.     
  419.     if single:
  420.         alltests = findtests(testdir, stdtests, nottests)
  421.         for i in range(len(alltests)):
  422.             if tests[0] == alltests[i]:
  423.                 if i == len(alltests) - 1:
  424.                     os.unlink(filename)
  425.                 else:
  426.                     fp = open(filename, 'w')
  427.                     fp.write(alltests[i + 1] + '\n')
  428.                     fp.close()
  429.                 break
  430.                 continue
  431.         
  432.     
  433.     if trace:
  434.         r = tracer.results()
  435.         r.write_results(show_missing = True, summary = True, coverdir = coverdir)
  436.     
  437.     if runleaks:
  438.         os.system('leaks %d' % os.getpid())
  439.     
  440.     sys.exit(len(bad) > 0)
  441.  
  442. STDTESTS = [
  443.     'test_grammar',
  444.     'test_opcodes',
  445.     'test_operations',
  446.     'test_builtin',
  447.     'test_exceptions',
  448.     'test_types']
  449. NOTTESTS = [
  450.     'test_support',
  451.     'test_future1',
  452.     'test_future2',
  453.     'test_future3']
  454.  
  455. def findtests(testdir = None, stdtests = STDTESTS, nottests = NOTTESTS):
  456.     '''Return a list of all applicable test modules.'''
  457.     if not testdir:
  458.         testdir = findtestdir()
  459.     
  460.     names = os.listdir(testdir)
  461.     tests = []
  462.     for name in names:
  463.         if name[:5] == 'test_' and name[-3:] == os.extsep + 'py':
  464.             modname = name[:-3]
  465.             if modname not in stdtests and modname not in nottests:
  466.                 tests.append(modname)
  467.             
  468.         modname not in nottests
  469.     
  470.     tests.sort()
  471.     return stdtests + tests
  472.  
  473.  
  474. def runtest(test, generate, verbose, quiet, testdir = None, huntrleaks = False):
  475.     """Run a single test.
  476.     test -- the name of the test
  477.     generate -- if true, generate output, instead of running the test
  478.     and comparing it to a previously created output file
  479.     verbose -- if true, print more messages
  480.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  481.     testdir -- test directory
  482.     """
  483.     test_support.unload(test)
  484.     if not testdir:
  485.         testdir = findtestdir()
  486.     
  487.     outputdir = os.path.join(testdir, 'output')
  488.     outputfile = os.path.join(outputdir, test)
  489.     if verbose:
  490.         cfp = None
  491.     else:
  492.         cfp = cStringIO.StringIO()
  493.     if huntrleaks:
  494.         refrep = open(huntrleaks[2], 'a')
  495.     
  496.     
  497.     try:
  498.         save_stdout = sys.stdout
  499.         
  500.         try:
  501.             if cfp:
  502.                 sys.stdout = cfp
  503.                 print test
  504.             
  505.             if test.startswith('test.'):
  506.                 abstest = test
  507.             else:
  508.                 abstest = 'test.' + test
  509.             the_package = __import__(abstest, globals(), locals(), [])
  510.             the_module = getattr(the_package, test)
  511.             indirect_test = getattr(the_module, 'test_main', None)
  512.             if indirect_test is not None:
  513.                 indirect_test()
  514.             
  515.             if huntrleaks:
  516.                 import copy_reg
  517.                 fs = warnings.filters[:]
  518.                 ps = copy_reg.dispatch_table.copy()
  519.                 pic = sys.path_importer_cache.copy()
  520.                 import gc
  521.                 
  522.                 def cleanup():
  523.                     import _strptime
  524.                     import urlparse
  525.                     import warnings
  526.                     import dircache
  527.                     _path_created = _path_created
  528.                     import distutils.dir_util
  529.                     _path_created.clear()
  530.                     warnings.filters[:] = fs
  531.                     gc.collect()
  532.                     sre.purge()
  533.                     _strptime._regex_cache.clear()
  534.                     urlparse.clear_cache()
  535.                     copy_reg.dispatch_table.clear()
  536.                     copy_reg.dispatch_table.update(ps)
  537.                     sys.path_importer_cache.clear()
  538.                     sys.path_importer_cache.update(pic)
  539.                     dircache.reset()
  540.  
  541.                 if indirect_test:
  542.                     
  543.                     def run_the_test():
  544.                         indirect_test()
  545.  
  546.                 else:
  547.                     
  548.                     def run_the_test():
  549.                         reload(the_module)
  550.  
  551.                 deltas = []
  552.                 repcount = huntrleaks[0] + huntrleaks[1]
  553.                 print >>sys.stderr, 'beginning', repcount, 'repetitions'
  554.                 print >>sys.stderr, '1234567890' * (repcount // 10 + 1)[:repcount]
  555.                 for i in range(repcount):
  556.                     rc = sys.gettotalrefcount()
  557.                     run_the_test()
  558.                     sys.stderr.write('.')
  559.                     cleanup()
  560.                     deltas.append(sys.gettotalrefcount() - rc - 2)
  561.                 
  562.                 print >>sys.stderr
  563.                 if max(map(abs, deltas[-huntrleaks[1]:])) > 0:
  564.                     print >>sys.stderr, test, 'leaked', deltas[-huntrleaks[1]:], 'references'
  565.                     print >>refrep, test, 'leaked', deltas[-huntrleaks[1]:], 'references'
  566.                 
  567.         finally:
  568.             sys.stdout = save_stdout
  569.  
  570.     except test_support.ResourceDenied:
  571.         msg = None
  572.         if not quiet:
  573.             print test, 'skipped --', msg
  574.             sys.stdout.flush()
  575.         
  576.         return -2
  577.     except (ImportError, test_support.TestSkipped):
  578.         msg = None
  579.         if not quiet:
  580.             print test, 'skipped --', msg
  581.             sys.stdout.flush()
  582.         
  583.         return -1
  584.     except KeyboardInterrupt:
  585.         raise 
  586.     except test_support.TestFailed:
  587.         msg = None
  588.         print 'test', test, 'failed --', msg
  589.         sys.stdout.flush()
  590.         return 0
  591.     except:
  592.         (type, value) = sys.exc_info()[:2]
  593.         print 'test', test, 'crashed --', str(type) + ':', value
  594.         sys.stdout.flush()
  595.         if verbose:
  596.             traceback.print_exc(file = sys.stdout)
  597.             sys.stdout.flush()
  598.         
  599.         return 0
  600.  
  601.     if not cfp:
  602.         return 1
  603.     
  604.     output = cfp.getvalue()
  605.     if generate:
  606.         if output == test + '\n':
  607.             if os.path.exists(outputfile):
  608.                 print 'output file', outputfile, 'is no longer needed; consider removing it'
  609.             else:
  610.                 return 1
  611.         
  612.         fp = open(outputfile, 'w')
  613.         fp.write(output)
  614.         fp.close()
  615.         return 1
  616.     
  617.     if os.path.exists(outputfile):
  618.         fp = open(outputfile, 'r')
  619.         expected = fp.read()
  620.         fp.close()
  621.     else:
  622.         expected = test + '\n'
  623.     if output == expected or huntrleaks:
  624.         return 1
  625.     
  626.     print 'test', test, 'produced unexpected output:'
  627.     sys.stdout.flush()
  628.     reportdiff(expected, output)
  629.     sys.stdout.flush()
  630.     return 0
  631.  
  632.  
  633. def reportdiff(expected, output):
  634.     import difflib
  635.     print '*' * 70
  636.     a = expected.splitlines(1)
  637.     b = output.splitlines(1)
  638.     sm = difflib.SequenceMatcher(a = a, b = b)
  639.     tuples = sm.get_opcodes()
  640.     
  641.     def pair(x0, x1):
  642.         x0 += 1
  643.         if x0 >= x1:
  644.             return 'line ' + str(x0)
  645.         else:
  646.             return 'lines %d-%d' % (x0, x1)
  647.  
  648.     for op, a0, a1, b0, b1 in tuples:
  649.         if op == 'equal':
  650.             continue
  651.         if op == 'delete':
  652.             print '***', pair(a0, a1), 'of expected output missing:'
  653.             for line in a[a0:a1]:
  654.                 print '-', line,
  655.             
  656.         if op == 'replace':
  657.             print '*** mismatch between', pair(a0, a1), 'of expected', 'output and', pair(b0, b1), 'of actual output:'
  658.             for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
  659.                 print line,
  660.             
  661.         if op == 'insert':
  662.             print '***', pair(b0, b1), "of actual output doesn't appear", 'in expected output after line', str(a1) + ':'
  663.             for line in b[b0:b1]:
  664.                 print '+', line,
  665.             
  666.         print 'get_opcodes() returned bad tuple?!?!', (op, a0, a1, b0, b1)
  667.     
  668.     print '*' * 70
  669.  
  670.  
  671. def findtestdir():
  672.     if __name__ == '__main__':
  673.         file = sys.argv[0]
  674.     else:
  675.         file = __file__
  676.     if not os.path.dirname(file):
  677.         pass
  678.     testdir = os.curdir
  679.     return testdir
  680.  
  681.  
  682. def removepy(name):
  683.     if name.endswith(os.extsep + 'py'):
  684.         name = name[:-3]
  685.     
  686.     return name
  687.  
  688.  
  689. def count(n, word):
  690.     if n == 1:
  691.         return '%d %s' % (n, word)
  692.     else:
  693.         return '%d %ss' % (n, word)
  694.  
  695.  
  696. def printlist(x, width = 70, indent = 4):
  697.     '''Print the elements of iterable x to stdout.
  698.  
  699.     Optional arg width (default 70) is the maximum line length.
  700.     Optional arg indent (default 4) is the number of blanks with which to
  701.     begin each line.
  702.     '''
  703.     fill = fill
  704.     import textwrap
  705.     blanks = ' ' * indent
  706.     print fill(' '.join(map(str, x)), width, initial_indent = blanks, subsequent_indent = blanks)
  707.  
  708. _expectations = {
  709.     'win32': '\n        test__locale\n        test_applesingle\n        test_al\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_gdbm\n        test_gl\n        test_grp\n        test_imgfile\n        test_ioctl\n        test_largefile\n        test_linuxaudiodev\n        test_mhlib\n        test_nis\n        test_openpty\n        test_ossaudiodev\n        test_poll\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_sunaudiodev\n        test_threadsignals\n        test_timing\n        ',
  710.     'linux2': '\n        test_al\n        test_applesingle\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_nis\n        test_ntpath\n        test_ossaudiodev\n        test_sunaudiodev\n        ',
  711.     'mac': '\n        test_al\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_cd\n        test_cl\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_gl\n        test_grp\n        test_ioctl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_mmap\n        test_nis\n        test_ntpath\n        test_openpty\n        test_ossaudiodev\n        test_poll\n        test_popen\n        test_popen2\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_sunaudiodev\n        test_sundry\n        test_tarfile\n        test_timing\n        ',
  712.     'unixware7': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sunaudiodev\n        test_sundry\n        ',
  713.     'openunix8': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sunaudiodev\n        test_sundry\n        ',
  714.     'sco_sv3': '\n        test_al\n        test_applesingle\n        test_asynchat\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_dl\n        test_fork1\n        test_gettext\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_queue\n        test_sax\n        test_sunaudiodev\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        ',
  715.     'riscos': '\n        test_al\n        test_applesingle\n        test_asynchat\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_commands\n        test_crypt\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_gdbm\n        test_gl\n        test_grp\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_mmap\n        test_nis\n        test_ntpath\n        test_openpty\n        test_poll\n        test_popen2\n        test_pty\n        test_pwd\n        test_strop\n        test_sunaudiodev\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        test_timing\n        ',
  716.     'darwin': '\n        test__locale\n        test_al\n        test_bsddb\n        test_bsddb3\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_minidom\n        test_nis\n        test_ntpath\n        test_ossaudiodev\n        test_poll\n        test_sunaudiodev\n        ',
  717.     'sunos5': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dbm\n        test_gdbm\n        test_gl\n        test_gzip\n        test_imgfile\n        test_linuxaudiodev\n        test_openpty\n        test_zipfile\n        test_zlib\n        ',
  718.     'hp-ux11': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gdbm\n        test_gl\n        test_gzip\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sunaudiodev\n        test_zipfile\n        test_zlib\n        ',
  719.     'atheos': '\n        test_al\n        test_applesingle\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_mhlib\n        test_mmap\n        test_nis\n        test_poll\n        test_popen2\n        test_resource\n        test_sunaudiodev\n        ',
  720.     'cygwin': '\n        test_al\n        test_applesingle\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_curses\n        test_dbm\n        test_gl\n        test_imgfile\n        test_ioctl\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_nis\n        test_ossaudiodev\n        test_socketserver\n        test_sunaudiodev\n        ',
  721.     'os2emx': '\n        test_al\n        test_applesingle\n        test_audioop\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_commands\n        test_curses\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_mhlib\n        test_mmap\n        test_nis\n        test_openpty\n        test_ossaudiodev\n        test_pty\n        test_resource\n        test_signal\n        test_sunaudiodev\n        ',
  722.     'freebsd4': '\n        test_aepack\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb3\n        test_cd\n        test_cl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_linuxaudiodev\n        test_locale\n        test_macfs\n        test_macostools\n        test_nis\n        test_normalization\n        test_ossaudiodev\n        test_pep277\n        test_plistlib\n        test_pty\n        test_scriptpackages\n        test_socket_ssl\n        test_socketserver\n        test_sunaudiodev\n        test_tcl\n        test_timeout\n        test_unicode_file\n        test_urllibnet\n        test_winreg\n        test_winsound\n        ',
  723.     'aix5': '\n        test_aepack\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_cd\n        test_cl\n        test_dl\n        test_gdbm\n        test_gl\n        test_gzip\n        test_imgfile\n        test_linuxaudiodev\n        test_macfs\n        test_macostools\n        test_nis\n        test_ossaudiodev\n        test_sunaudiodev\n        test_tcl\n        test_winreg\n        test_winsound\n        test_zipimport\n        test_zlib\n        ' }
  724. _expectations['freebsd5'] = _expectations['freebsd4']
  725. _expectations['freebsd6'] = _expectations['freebsd4']
  726.  
  727. class _ExpectedSkips:
  728.     
  729.     def __init__(self):
  730.         import os.path as os
  731.         test_normalization = test_normalization
  732.         import test
  733.         test_socket_ssl = test_socket_ssl
  734.         import test
  735.         test_timeout = test_timeout
  736.         import test
  737.         test_codecmaps_cn = test_codecmaps_cn
  738.         test_codecmaps_jp = test_codecmaps_jp
  739.         import test
  740.         test_codecmaps_kr = test_codecmaps_kr
  741.         test_codecmaps_tw = test_codecmaps_tw
  742.         import test
  743.         test_codecmaps_hk = test_codecmaps_hk
  744.         import test
  745.         self.valid = False
  746.         if sys.platform in _expectations:
  747.             s = _expectations[sys.platform]
  748.             self.expected = set(s.split())
  749.             if not os.path.supports_unicode_filenames:
  750.                 self.expected.add('test_pep277')
  751.             
  752.             if test_normalization.skip_expected:
  753.                 self.expected.add('test_normalization')
  754.             
  755.             if test_socket_ssl.skip_expected:
  756.                 self.expected.add('test_socket_ssl')
  757.             
  758.             if test_timeout.skip_expected:
  759.                 self.expected.add('test_timeout')
  760.             
  761.             for cc in ('cn', 'jp', 'kr', 'tw', 'hk'):
  762.                 if eval('test_codecmaps_' + cc).skip_expected:
  763.                     self.expected.add('test_codecmaps_' + cc)
  764.                     continue
  765.             
  766.             if sys.maxint == 0x7FFFFFFFFFFFFFFFL:
  767.                 self.expected.add('test_rgbimg')
  768.                 self.expected.add('test_imageop')
  769.             
  770.             if sys.platform not in ('mac', 'darwin'):
  771.                 MAC_ONLY = [
  772.                     'test_macostools',
  773.                     'test_macfs',
  774.                     'test_aepack',
  775.                     'test_plistlib',
  776.                     'test_scriptpackages']
  777.                 for skip in MAC_ONLY:
  778.                     self.expected.add(skip)
  779.                 
  780.             
  781.             if sys.platform != 'win32':
  782.                 WIN_ONLY = [
  783.                     'test_unicode_file',
  784.                     'test_winreg',
  785.                     'test_winsound']
  786.                 for skip in WIN_ONLY:
  787.                     self.expected.add(skip)
  788.                 
  789.             
  790.             self.valid = True
  791.         
  792.  
  793.     
  794.     def isvalid(self):
  795.         '''Return true iff _ExpectedSkips knows about the current platform.'''
  796.         return self.valid
  797.  
  798.     
  799.     def getexpected(self):
  800.         '''Return set of test names we expect to skip on current platform.
  801.  
  802.         self.isvalid() must be true.
  803.         '''
  804.         if not self.isvalid():
  805.             raise AssertionError
  806.         return self.expected
  807.  
  808.  
  809. if __name__ == '__main__':
  810.     mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
  811.     i = pathlen = len(sys.path)
  812.     while i >= 0:
  813.         i -= 1
  814.         if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
  815.             del sys.path[i]
  816.         
  817.     if len(sys.path) == pathlen:
  818.         print 'Could not find %r in sys.path to remove it' % mydir
  819.     
  820.     main()
  821.  
  822.